<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>canvas刮刮乐</title>
    <style>
        * {
            margin: 0;
        }

        body {
            text-align: center;
        }

        #myCanvas {
            border: 1px solid #000;
        }
    </style>
</head>

<body>
    <canvas width="300" height="300" id="myCanvas"></canvas>
</body>
<script>

    var myCanvas = document.getElementById("myCanvas");
    var myCanvasW = myCanvas.width;
    var myCanvasH = myCanvas.height;
    var ctx = myCanvas.getContext("2d");
    var lastX,  //上一个鼠标x轴坐标
        lastY,  //上一个鼠标Y轴坐标
        nowX,   //下一个鼠标x轴坐标
        nowY;   //下一个鼠标y轴坐标

    //画遮罩层
    ctx.fillStyle = "#ccc";
    ctx.fillRect(0, 0, myCanvasW, myCanvasH);

    //给canvas随机设置背景图片
    var img = new Image();
    img.src = Math.random() < 0.5 ? img.src = "./1.jpg" : img.src = "./2.jpg";
    myCanvas.style.backgroundImage = "url(" + img.src + ")";
    myCanvas.style.backgroundSize = "cover";
    img.onload = function () {
        //刮
        //(1)、设置新旧canvas画布上的图形合成后的显示形式
        ctx.globalCompositeOperation = "destination-out";

        //(2)、鼠标按下就以鼠标位置坐标为中心点画半径为20的圆
        myCanvas.addEventListener("mousedown", downFn, false);
    }


    function downFn(e) {
        var lastX = e.clientX - myCanvas.offsetLeft;
        var lastY = e.clientY - myCanvas.offsetTop;

        //ctx.beginPath();  //如果这里开启一个新的路径会出现崩裂效果
        ctx.arc(lastX, lastY, 20, 0, Math.PI * 2, 0);
        ctx.fill();


        //(3)、鼠标移动也以鼠标位置坐标为中心点画半径为20的圆
        myCanvas.addEventListener("mousemove", moveFn, false);

        //(4)、鼠标抬起时
        document.addEventListener("mouseup", upFn, false);

    }

    function moveFn(e) {
        var nowX = e.clientX - myCanvas.offsetLeft;
        var nowY = e.clientY - myCanvas.offsetTop;

        //在这里开启新路径，不会出现崩裂效果
        //画以上一个鼠标移动坐标的圆和以下一个（现在的）鼠标的圆画宽度为圆直径的线段
        ctx.beginPath();
        ctx.lineWidth = 40;
        ctx.moveTo(lastX, lastY);
        ctx.lineTo(nowX, nowY);
        ctx.stroke();

        ctx.arc(nowX, nowY, 20, 0, Math.PI * 2, 0);
        ctx.closePath();
        ctx.fill();
         //(5)、写到现在会出现一个问题，如果鼠标移动过快会出现断点现象，原因是移动过快，中间有的圆没有画上，解决方法是以上一个鼠标移动坐标的圆和以下一个（现在的）鼠标的圆画宽度为圆直径的线段

        lastX = nowX;
        lastY = nowY;

    }

    function upFn() {
        myCanvas.removeEventListener("mousemove", moveFn, false);
        document.removeEventListener("mouseup", upFn, false);
    }




</script>

</html>